package com.jingbit.ai.utils;

import static android.content.Context.BATTERY_SERVICE;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.bluetooth.BluetoothAdapter;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.format.Formatter;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;

import com.jingbit.ai.AIApp;
import com.jingbit.ai.bean.AppInfo;
import com.jingbit.ai.bean.ContactInfo;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;


public class AppUtil {
    public static List<AppInfo> appList = new ArrayList();
    public static List<ContactInfo> contacts = new ArrayList();

    public static ContactInfo getContact(Context context, String keyword) {
        ContentResolver resolver = context.getContentResolver();
        Cursor cursor = resolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            do {
                // 获取联系人ID和名称
                String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                // 根据联系人ID查询联系人电话号码
                Cursor phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?", new String[]{contactId}, null);
                if (phoneCursor != null && phoneCursor.moveToFirst()) {
                    do {
                        // 获取电话号码
                        String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(
                                ContactsContract.CommonDataKinds.Phone.NUMBER));
                        if (phoneNumber.contains(keyword) || name.contains(keyword)) {
                            ContactInfo contactInfo = new ContactInfo();
                            contactInfo.setName(name);
                            // 处理电话号码
                            contactInfo.addPhone(phoneNumber);
                            phoneCursor.close();
                            cursor.close();
                            return contactInfo;
                        }
                    } while (phoneCursor.moveToNext());
                    phoneCursor.close();
                }
            } while (cursor.moveToNext());
            cursor.close();
        }
        return null;
    }

    public static AppInfo getApp(Context ctx, String keyword) {
        PackageManager packageManager = ctx.getPackageManager();
        List<PackageInfo> installedPackageList = packageManager.getInstalledPackages(0);

        for (PackageInfo packageInfo : installedPackageList) {
            if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                String appName = packageInfo.applicationInfo.loadLabel(packageManager).toString();
                String packageName = packageInfo.packageName;
                if (appName.contains(keyword)) {
                    AppInfo appInfo = new AppInfo();
                    appInfo.setAppName(appName);
                    appInfo.setPackageName(packageName);
                    return appInfo;
                }
            }
        }
        return null;
    }

    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        if (activityManager.getRunningAppProcesses() == null) {
            return null;
        }

        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager
                .getRunningAppProcesses()) {
            if (appProcess.pid == pid) {

                return appProcess.processName;
            }
        }
        return null;
    }


    public static long getFirstInstallTimeInSecond(Context context) {
        try {
            final PackageManager pm = context.getPackageManager();
            final PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            return pi.firstInstallTime >= 1000000000000L ? pi.firstInstallTime / 1000L : pi.firstInstallTime;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public static String encodeString(String content) {
        String result = null;

        try {
            result = URLEncoder.encode(content, "utf-8");
        } catch (UnsupportedEncodingException var3) {
            var3.printStackTrace();
        }

        return result;
    }

    public static long getLastUpdateTimeInSecond(Context context) {
        try {
            final PackageManager pm = context.getPackageManager();
            final PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            return pi.lastUpdateTime >= 1000000000000L ? pi.lastUpdateTime / 1000L : pi.lastUpdateTime;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 包名
     *
     * @return
     */
    public static String getPackageName(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            if (packageInfo != null) {
                return packageInfo.packageName;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static PackageInfo getPackageInfo(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 版本名
     *
     * @return
     */
    public static String getVersionName(Context context) {
        PackageInfo packageInfo = getPackageInfo(context);
        if (packageInfo != null) {
            return packageInfo.versionName;
        }
        return "";
    }

    /**
     * 版本名
     *
     * @return
     */
    public static String getAppName(Context context) {
        PackageInfo packageInfo = getPackageInfo(context);
        if (packageInfo != null) {
            int label = packageInfo.applicationInfo.labelRes;
            return context.getString(label);
        }
        return "";
    }

    /**
     * 版本号
     *
     * @return
     */
    public static long getVersionCode(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            if (packageInfo != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    return packageInfo.getLongVersionCode();
                } else {
                    return packageInfo.versionCode;
                }

            }
        } catch (Exception ignored) {
        }
        return 0;
    }

    /**
     * 获取安装时间
     */
    public long getFirstInstallTime(Context context) {
        PackageInfo packageInfo = getPackageInfo(context);
        if (packageInfo != null) {
            return packageInfo.firstInstallTime;
        }
        return 0;
    }

    public static boolean isAppInstalled(Context ctx, String packageName) {
        try {
            return ctx.getPackageManager().getPackageInfo(packageName, 0) != null;
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isNewUser(Context context) {
        PackageManager pm = context.getPackageManager();
        PackageInfo pi;
        try {
            pi = pm.getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return true;
        }
        return pi != null && pi.firstInstallTime == pi.lastUpdateTime;

    }

    public static String visitURL(String url, String format) {
        String urlDate = null;
        try {
            URL url1 = new URL(url);
            //生成连接对象
            URLConnection conn = url1.openConnection();
            //连接对象网页
            conn.connect();
            //获取对象网址时间
            Date date = new Date(conn.getDate());
            //设置日期格式
            SimpleDateFormat df = new SimpleDateFormat(format);
            urlDate = df.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return urlDate;
    }

    public static void killProcess(Context context, String packageName) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : runningAppProcesses) {
            if (processInfo.processName.equals(packageName)) {
                android.os.Process.killProcess(processInfo.pid);
                break;
            }
        }
    }

    public static void startApp(Context context, String packageName) {
        PackageManager packageManager = context.getPackageManager();
        Intent intent = packageManager.getLaunchIntentForPackage(packageName);
        if (intent != null) {
            context.startActivity(intent);
        }
    }

    public static void startAppWithExtra(Context context, String packageName, String extraKey, String extraValue) {
        PackageManager packageManager = context.getPackageManager();
        Intent intent = packageManager.getLaunchIntentForPackage(packageName);
        if (intent != null) {
            intent.putExtra(extraKey, extraValue);
            context.startActivity(intent);
        }
    }

    public static void shutdownDevice(Context context) {
        Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.sendBroadcast(intent);
    }


    public static boolean lightdown(Context ctx) {
        // 获取设备管理器
//        DevicePolicyManager devicePolicyManager = (DevicePolicyManager)ctx.getSystemService(Context.DEVICE_POLICY_SERVICE);
//        // 检查是否有权限
//        if (devicePolicyManager.isAdminActive(mAdminName)) {
//            // 让设备进入休眠状态
//            devicePolicyManager.lockNow();
//        } else {
//            // 弹出请求激活设备管理器的对话框
//            Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
//            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mAdminName);
//            intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "为了让应用正常运行，请激活设备管理器");
//            startActivity(intent);
//        }
        return true;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static boolean controlLighter(Context context, boolean open) throws CameraAccessException {
        // 获取相机服务对象
        CameraManager cameraManager = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 获取相机 ID 列表
                String cameraId = cameraManager.getCameraIdList()[0];
                // 打开手电筒
                cameraManager.setTorchMode(cameraId, open);
            }
        }
        return false;
    }

    public static int getVolume(Context ctx) {
        // 获取音频管理器对象
        AudioManager audioManager = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
        // 获取最大音量
        return audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    }

    public static void setVolume(Context ctx, boolean low) {
        // 获取音频管理器对象
        AudioManager audioManager = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
        // 获取当前音量
        int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        // 获取最大音量
        int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        if (low) {
            currentVolume = currentVolume < 10 ? 0 : currentVolume - 10;
        } else {
            currentVolume = currentVolume >= maxVolume ? 100 : currentVolume + 10;
        }

        setVolumeByVol(ctx, currentVolume);
    }

    public static void setVolumeByVol(Context ctx, int volume) {
        AudioManager audioManager = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
        // 调整音量，flags 参数决定了是否显示调节音量的 UI
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, AudioManager.FLAG_SHOW_UI);
    }

    //不自动弹出软键盘
    public static void softInputMode(Activity activity) {
        activity.getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
                        WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    }

    //保持屏幕常亮
    public static void setScreenLightHolding(Activity activity) {
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    public static void setScreenLightValue(Context ctx, boolean down) {
        try {
            // 获取当前屏幕亮度值
            int currentBrightness = Settings.System.getInt(ctx.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
            setAutoScreenLightMode(ctx, false);
            if (down) {
                currentBrightness = currentBrightness < 25.5 ? 0 : currentBrightness - 25;
            } else {
                currentBrightness = currentBrightness >= 255 ? 255 : (int) (currentBrightness + 25.5);
            }
            // 设置屏幕亮度值，value 的值在 0-255 之间
            Settings.System.putInt(ctx.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, currentBrightness);

        } catch (Exception e) {
        }

    }

    public static void setAutoScreenLightMode(Context ctx, boolean auto) {
        // 判断当前是否为自动亮度调节模式
        if (auto) {
            // 关闭自动亮度调节模式
            Settings.System.putInt(ctx.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
        } else {
            // 开启自动亮度调节模式
            Settings.System.putInt(ctx.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
        }
    }

    public static void setRingerMode(Context ctx, int mode) {
        // 判断当前是否为自动亮度调节模式
        AudioManager audioManager = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
        audioManager.setRingerMode(mode);
    }

    public static void setCameraMode(Context ctx, int mode) {
    }

    //获取屏幕分辨率
    public static int[] defaultDisplay(Activity activity) {
        int[] pixels = new int[2];
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        pixels[0] = dm.widthPixels;
        pixels[1] = dm.heightPixels;
        return pixels;
    }

    //获取Android系统版本
    public static String getSystemVersion() {
        return android.os.Build.VERSION.RELEASE;
    }

    //获取设备机型
    public static String getSystemModel() {
        return android.os.Build.MODEL;
    }

    //获取系统当前语言
    public static String getSystemLanguage() {
        return Locale.getDefault().getLanguage();
    }

    //获取设备电量
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public static int getBattery(Context context) {
        BatteryManager batteryManager =
                (BatteryManager) context.getSystemService(BATTERY_SERVICE);
        return batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
    }

    //获取设备内存可用大小(GB)
    public static String getRomAvailableSize(Context context) {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return Formatter.formatFileSize(context, blockSize * availableBlocks);
    }

    //获取设备内存可用的总量大小(GB)
    public static String getRomTotalSize(Context context) {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        return Formatter.formatFileSize(context, blockSize * totalBlocks);
    }

    //获得SD卡可用总量大小
    public static String getSDTotalSize(Context context) {
        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        return Formatter.formatFileSize(context, blockSize * totalBlocks);
    }

    //获得sd卡可用大小
    private String getSDAvailableSize(Context context) {
        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return Formatter.formatFileSize(context, blockSize * availableBlocks);
    }

    //重启设备
    private void restartDevices() {
        String cmd = "su -c reboot";
        try {
            Runtime.getRuntime().exec(cmd);
        } catch (IOException e) {
            e.printStackTrace();
            Log.i("restart", "权限不足");
        }
    }

    /**
     * 拨打电话（跳转到拨号界面，用户手动点击拨打）
     *
     * @param phoneNum 电话号码
     */
    public static void callPhone(Context context, String phoneNum) {
        Log.d(AIApp.TAG, "callPhone: " + context + "---" + phoneNum);
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        context.startActivity(intent);
    }

    public static void sendSMS(Context context, String phone, String message) {
        Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phone));
        intent.putExtra("sms_body", message); // 短信内容
        context.startActivity(intent);
    }


    public static int getBluToothState() {
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter != null) {
            return mBluetoothAdapter.getState();
        }
        return 0;
    }

    public static boolean getWIFIState(Context ctx) {
        ConnectivityManager connManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected()) {
            // 当前设备已连接到 Wi-Fi
            return true;
        }
        return false;
    }
}
